----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------

SocialWindowTabFriends = {}
SocialWindowTabFriends.playerListData = {}
SocialWindowTabFriends.playerListOrder = {}

-- Sorting Parameters for the Player List
SocialWindowTabFriends.SORT_TYPE_NAME	 		= 1
SocialWindowTabFriends.SORT_TYPE_RANK			= 2
SocialWindowTabFriends.SORT_TYPE_CAREER	        = 3
SocialWindowTabFriends.SORT_TYPE_ONLINE	        = 4
SocialWindowTabFriends.SORT_TYPE_MAX_NUMBER     = 4

SocialWindowTabFriends.FILTER_MEMBERS_ALL	    = 1
SocialWindowTabFriends.FILTER_MAX_NUMBER		= 1

SocialWindowTabFriends.SORT_ORDER_UP	        = 1
SocialWindowTabFriends.SORT_ORDER_DOWN	        = 2

SocialWindowTabFriends.sortButtons = {  "SocialWindowTabFriendsSortButtonBarNameButton",		-- Order List Header 
                                    "SocialWindowTabFriendsSortButtonBarRankButton", 
                                    "SocialWindowTabFriendsSortButtonBarCareerButton", 
                                    "SocialWindowTabFriendsSortButtonBarOnlineButton" }
-- Make sure these match the ID numbers in the XML definition 
--    For example,  <Button name="$parentNameButton" inherits="SocialHeaderButton" id="1"> 
SocialWindowTabFriends.sortKeys = {"name",
                               "rankString", 
                               "career", 
                               "onlineString"  }

SocialWindowTabFriends.sortColumns = { "Name", 
                                   "Rank", 
                                   "Career", 
                                   "Online"  }
                                   
SocialWindowTabFriends.display = { type=SocialWindowTabFriends.SORT_TYPE_NAME, 
                                  order=SocialWindowTabFriends.SORT_ORDER_UP, 
                                  filter=SocialWindowTabFriends.FILTER_MEMBERS_ALL }
                                
SocialWindowTabFriends.ColumnHeaders = {   
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_NAME),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_RANK),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_CAREER),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_LOCATION) }
                                      
SocialWindowTabFriends.SelectedPlayerDataIndex    = 0
SocialWindowTabFriends.SelectedFriendsName        = L""
SocialWindowTabFriends.NumberOfFriends			  = 0
                    
local function InitPlayerListData()
    SocialWindowTabFriends.playerListData = {}
        
    local FriendsListData = GetFriendsList()
    
    SocialWindowTabFriends.NumberOfFriends = 0

     if ( FriendsListData ~= nil ) then
        for key, value in ipairs( FriendsListData ) do
            -- These should match the data that was retrived from war_interface::LuaGetFriendsList
            SocialWindowTabFriends.playerListData[key] = {}
			SocialWindowTabFriends.NumberOfFriends = SocialWindowTabFriends.NumberOfFriends +1
            SocialWindowTabFriends.playerListData[key].name = value.name
            SocialWindowTabFriends.playerListData[key].career = value.careerName
            if (value.careerName == L"") then
                SocialWindowTabFriends.playerListData[key].rankString = L""
            else
                SocialWindowTabFriends.playerListData[key].rankString = L""..value.rank
                -- if the person is offline the Rank is invalid, so don't display anything in the list
            end
            if ( value.zoneID ~= 0 ) then
                SocialWindowTabFriends.playerListData[key].onlineString = GetZoneName( value.zoneID )
            else
                SocialWindowTabFriends.playerListData[key].onlineString = GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_WINDOW_OFFLINE)
            end
            if (value.guildName == nil) then
                SocialWindowTabFriends.playerListData[key].guildName = L""
            else
                SocialWindowTabFriends.playerListData[key].guildName = value.guildName
            end
        end
    end
    
end
-- This function is used as the comparison function for 
-- table.sort() on the player display order
local function ComparePlayers( index1, index2 )

    if( index2 == nil ) then
        return false
    end

    local player1 = SocialWindowTabFriends.playerListData[index1]
    local player2 = SocialWindowTabFriends.playerListData[index2]
    
    if (player1 == nil or player1.name == nil or player1.name == L"") then
        return false
    end
    
    if (player2 == nil or player2.name == nil or player2.name == L"") then
        return true
    end
    
    local type = SocialWindowTabFriends.display.type
    local order = SocialWindowTabFriends.display.order
    
    local compareResult
-- Check for sorting by all the the string fields first
    
    -- Sorting by Name
    if( type == SocialWindowTabFriends.SORT_TYPE_NAME )then
        if( order == SocialWindowTabFriends.SORT_ORDER_UP ) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        else
            return ( WStringsCompare(player1.name, player2.name) > 0 )
        end
    end
    
    --Sorting By Career (And if they match, then sort alphabetically)
    if( type == SocialWindowTabFriends.SORT_TYPE_CAREER ) then
        compareResult = WStringsCompare(player1.careerName, player2.careerName)
        
        if (compareResult == 0) then
            if( order == SocialWindowTabFriends.SORT_ORDER_UP ) then
                compareResult = WStringsCompare(player1.name, player2.name)
            end
        end
        
        if( order == SocialWindowTabFriends.SORT_ORDER_UP ) then
            return ( compareResult < 0 )
        else
            return ( compareResult > 0 )
        end		
    end

    -- Sorting By Online (And if they match, then sort alphabetically)
    if( type == SocialWindowTabFriends.SORT_TYPE_ONLINE ) then
        compareResult = WStringsCompare(player1.onlineString, player2.onlineString)
        if (compareResult == 0) then
                compareResult = WStringsCompare(player1.name, player2.name)
        end
        
        if( order == SocialWindowTabFriends.SORT_ORDER_UP ) then
            return ( compareResult < 0)
        else
            return ( compareResult > 0)
        end
    end

    -- Otherwise assume we're sorting by a number, not a string.
    -- Sorting By A Numerical Value - When tied, sort by name
    local key = SocialWindowTabFriends.sortKeys[type]
    if( tonumber(player1[key]) == tonumber(player2[key]) ) then
        compareResult = WStringsCompare(player1.name, player2.name)
    else		
        if ( tonumber(player1[key]) < tonumber(player2[key]) ) then
            compareResult = -1
        else
            compareResult = 1
        end
    end
    
    if( order == SocialWindowTabSearch.SORT_ORDER_UP ) then
        return ( compareResult < 0)
    else
        return ( compareResult > 0)
    end
end

local function SortPlayerList()	
    table.sort( SocialWindowTabFriends.playerListOrder, ComparePlayers )
end

local function FilterPlayerList()	
    
    local filter = SocialWindowTabFriends.display.filter

    SocialWindowTabFriends.playerListOrder = {}
    for dataIndex, data in ipairs( SocialWindowTabFriends.playerListData ) do
        table.insert(SocialWindowTabFriends.playerListOrder, dataIndex)
    end
end

local function UpdatePlayerList()
    -- Filter, Sort, and Update
    InitPlayerListData()
    SocialWindowTabFriends.display.filter = SocialWindowTabFriends.FILTER_MEMBERS_ALL
    FilterPlayerList()
    SortPlayerList()

    ListBoxSetDisplayOrder( "SocialWindowTabFriendsList", SocialWindowTabFriends.playerListOrder )
end

-- OnInitialize Handler
function SocialWindowTabFriends.Initialize()

    -- Set all the header labels    
    LabelSetText( "SocialWindowTabFriendsPlayerSearchLabel", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SEARCH_EDITBOX_PLAYER_HEADER) )
    ButtonSetText( "SocialWindowTabFriendsCommandAddFriendButton",  GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_FRIENDS_BUTTON_ADDFRIEND) )
    ButtonSetText( "SocialWindowTabFriendsCommandRemoveFriendButton",  GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_FRIENDS_BUTTON_REMOVEFRIEND) )
    ButtonSetText( "SocialWindowTabFriendsSortButtonBarNameButton",  GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_NAME) )
    ButtonSetText( "SocialWindowTabFriendsSortButtonBarRankButton",	GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_RANK) )
    ButtonSetText( "SocialWindowTabFriendsSortButtonBarCareerButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_CAREER) )
    ButtonSetText( "SocialWindowTabFriendsSortButtonBarOnlineButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_LOCATION) )
    
    
    WindowRegisterEventHandler( "SocialWindow", SystemData.Events.SOCIAL_FRIENDS_UPDATED, "SocialWindowTabFriends.OnFriendsUpdated")
    
    WindowSetTintColor("SocialWindowTabFriendsSearchBackground", 0, 0, 0 )
    
    SocialWindowTabFriends.OnFriendsUpdated()
    SocialWindowTabFriends.UpdateSortButtons()
end

function SocialWindowTabFriends.Shutdown()

end

function SocialWindowTabFriends.OnClose()
    SocialWindowTabFriends.ResetEditBoxes()	-- Clear the edit box texts and any focus these edit boxes may have
end

function SocialWindowTabFriends.OnKeyEscape()
    SocialWindowTabFriends.ResetEditBoxes()	-- Clear the edit box texts and any focus these edit boxes may have
end

function SocialWindowTabFriends.UpdateSelectedPlayerData( dataIndex )

    -- Set the label values
    if (dataIndex ~= nil and dataIndex ~= 0) 
    then
        SocialWindowTabFriends.SelectedPlayerDataIndex = dataIndex
        SocialWindowTabFriends.SelectedFriendsName = SocialWindowTabFriends.playerListData[dataIndex].name
    else
        SocialWindowTabFriends.SelectedPlayerDataIndex = 0
        SocialWindowTabFriends.SelectedFriendsName = L""
    end
   
    SocialWindowTabFriends.UpdateSelectedRow()
end


function SocialWindowTabFriends.SetListRowTints()
	local targetRowWindow = L""

    for row = 1, SocialWindowTabFriendsList.numVisibleRows 
    do
        local row_mod = math.mod(row, 2)
        color = DataUtils.GetAlternatingRowColor( row_mod )
        
        targetRowWindow = "SocialWindowTabFriendsListRow"..row
        WindowSetTintColor(targetRowWindow.."Background", color.r, color.g, color.b )
        WindowSetAlpha(targetRowWindow.."Background", color.a )
    end
end


-- Callback from the <List> that updates a single row.
function SocialWindowTabFriends.UpdatePlayerRow()

    if (SocialWindowTabFriendsList.PopulatorIndices == nil) 
    then
        return
    end

    for rowIndex, dataIndex in ipairs (SocialWindowTabFriendsList.PopulatorIndices) 
    do
        local rowName = "SocialWindowTabFriendsListRow"..rowIndex

            -- Change colors based on if the guild member is selected/unselected, or offline            
        local labelColor = DefaultColor.WHITE           -- Default Online Memebers are white            
        
        local labelOnlineText = LabelGetText(rowName.."Online")
        if ( WStringsCompare( labelOnlineText, GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_WINDOW_OFFLINE) ) == 0 ) 
        then
            labelColor = DefaultColor.MEDIUM_LIGHT_GRAY		-- Offline Members are grey
        end                       
        
        LabelSetTextColor( rowName.."Name", labelColor.r, labelColor.g, labelColor.b)
        LabelSetTextColor( rowName.."Rank", labelColor.r, labelColor.g, labelColor.b)
        LabelSetTextColor( rowName.."Career", labelColor.r, labelColor.g, labelColor.b)
        LabelSetTextColor( rowName.."Online", labelColor.r, labelColor.g, labelColor.b)
            
    end
    
    SocialWindowTabFriends.SetListRowTints()
    SocialWindowTabFriends.UpdateSelectedRow()
end


function SocialWindowTabFriends.UpdateSelectedRow()

    if( nil == SocialWindowTabFriendsList.PopulatorIndices )
    then
        return
    end
    
    -- Setup the Custom formating for each row
    for rowIndex, dataIndex in ipairs( SocialWindowTabFriendsList.PopulatorIndices ) 
    do    
        local selected = SocialWindowTabFriends.SelectedPlayerDataIndex == dataIndex
        
        local rowName   = "SocialWindowTabFriendsListRow"..rowIndex

        ButtonSetPressedFlag(rowName, selected )
        ButtonSetStayDownFlag(rowName, selected )
    end
    
end

function SocialWindowTabFriends.OnFriendsUpdated()
    SocialWindowTabFriends.playerListNeedsUpdate = true
    UpdatePlayerList()

    -- Set sort button flags
    for index = 2, SocialWindowTabFriends.SORT_TYPE_MAX_NUMBER do
        local window = SocialWindowTabFriends.sortButtons[index]
        ButtonSetStayDownFlag( window, true )
    end
    
    SocialWindowTabFriends.UpdateSortButtons()
end

-- Displays the clicked sort button as pressed down and positions an arrow above it
function SocialWindowTabFriends.UpdateSortButtons()
    
    local type = SocialWindowTabFriends.display.type
    local order = SocialWindowTabFriends.display.order

    for index = 2, SocialWindowTabFriends.SORT_TYPE_MAX_NUMBER do
        local window = SocialWindowTabFriends.sortButtons[index]
        ButtonSetPressedFlag( window, index == SocialWindowTabFriends.display.type )
    end
    
    -- Update the Arrow
     WindowSetShowing( "SocialWindowTabFriendsSortButtonBarUpArrow", order == SocialWindowTabFriends.SORT_ORDER_UP )
    WindowSetShowing( "SocialWindowTabFriendsSortButtonBarDownArrow", order == SocialWindowTabFriends.SORT_ORDER_DOWN )

    local window = SocialWindowTabFriends.sortButtons[type]

    if( order == SocialWindowTabFriends.SORT_ORDER_UP ) then		
        WindowClearAnchors( "SocialWindowTabFriendsSortButtonBarUpArrow" )
        WindowAddAnchor("SocialWindowTabFriendsSortButtonBarUpArrow", "left", window, "left", 0, 0 )
    else
        WindowClearAnchors( "SocialWindowTabFriendsSortButtonBarDownArrow" )
        WindowAddAnchor("SocialWindowTabFriendsSortButtonBarDownArrow", "right", window, "right", 0, 0 )
    end

end

function SocialWindowTabFriends.OnMouseOverPlayerRow()
    -- Do nothing for now
end

function SocialWindowTabFriends.OnMouseOverPlayerRowEnd()
    -- Do nothing for now
end

function SocialWindowTabFriends.ResetEditBoxes()
    TextEditBoxSetText("SocialWindowTabFriendsPlayerSearchEditBox", L"")	-- Clear the Text from the Player Search Edit Box
    WindowAssignFocus("SocialWindowTabFriendsPlayerSearchEditBox", false)
    
	SocialWindowTabFriends.UpdateSelectedPlayerData()
	SocialWindowTabFriends.UpdatePlayerRow()
end

-- Handles the Left Button click on a player row
function SocialWindowTabFriends.OnLButtonUpPlayerRow()

    -- Convert the Row index to the data index
	local rowNum = WindowGetId( SystemData.ActiveWindow.name )	
	local dataIndex = SocialWindowTabFriendsList.PopulatorIndices[ rowNum ]
	
    SocialWindowTabFriends.UpdateSelectedPlayerData(dataIndex)
end

-- Handles the Right Button click on a player row
function SocialWindowTabFriends.OnRButtonUpPlayerRow()
    --DEBUG(L"EnteredGuildWindowTabRoster.OnRButtonUpPlayerRow")
    
    -- Convert the Row index to the data index
	local rowNum = WindowGetId( SystemData.ActiveWindow.name )	
	local dataIndex = SocialWindowTabFriendsList.PopulatorIndices[ rowNum ]
	
    SocialWindowTabFriends.UpdateSelectedPlayerData(dataIndex)
    
    if( SocialWindowTabFriends.SelectedFriendsName ~= L"" ) then
        PlayerMenuWindow.ShowMenu( SocialWindowTabFriends.SelectedFriendsName, 0, false, true ) 
    end
end

-- Displays a tooltip with information on the type of sort being hovered over
function SocialWindowTabFriends.OnMouseOverSortButton()
    local windowName	= SystemData.ActiveWindow.name
    local windowIndex	= WindowGetId (windowName)

    Tooltips.CreateTextOnlyTooltip (windowName, nil)
    Tooltips.SetTooltipText (1, 1, SocialWindowTabFriends.ColumnHeaders[windowIndex])
    Tooltips.SetTooltipColorDef (1, 1, Tooltips.COLOR_HEADING)	
    Tooltips.Finalize ()
    
    local anchor = { Point="top", RelativeTo=windowName, RelativePoint="center", XOffset=0, YOffset=-32 }
    Tooltips.AnchorTooltip (anchor)
    Tooltips.SetTooltipAlpha (1)
end

-- Button Callback for the Sort Buttons
function SocialWindowTabFriends.OnSortPlayerList()
    local type = WindowGetId( SystemData.ActiveWindow.name )
    -- If we are already using this sort type, toggle the order.
    if( type == SocialWindowTabFriends.display.type ) then
        if( SocialWindowTabFriends.display.order == SocialWindowTabFriends.SORT_ORDER_UP ) then
            SocialWindowTabFriends.display.order = SocialWindowTabFriends.SORT_ORDER_DOWN
        else
            SocialWindowTabFriends.display.order = SocialWindowTabFriends.SORT_ORDER_UP
        end
        
    -- Otherwise change the type and use the up order.	
    else
        SocialWindowTabFriends.display.type = type
        SocialWindowTabFriends.display.order = SocialWindowTabFriends.SORT_ORDER_UP
    end

    SocialWindowTabFriends.playerListNeedsUpdate = true
    UpdatePlayerList()
    SocialWindowTabFriends.UpdateSortButtons()
end
function SocialWindowTabFriends.AddFriend()
    if (SocialWindowTabFriendsPlayerSearchEditBox.Text == nil or SocialWindowTabFriendsPlayerSearchEditBox.Text == L"") then
        return
    end
    SystemData.UserInput.ChatText = L"/friendadd "..SocialWindowTabFriendsPlayerSearchEditBox.Text
    BroadcastEvent( SystemData.Events.SEND_CHAT_TEXT )
    SocialWindowTabFriends.ResetEditBoxes()
end

function SocialWindowTabFriends.RemoveFriend()
    if (SocialWindowTabFriends.SelectedPlayerDataIndex == 0) then
        return
    end
    
    local selectPlayerName = SocialWindowTabFriends.playerListData[SocialWindowTabFriends.SelectedPlayerDataIndex].name
    SystemData.UserInput.ChatText = L"/friendremove "..selectPlayerName
    BroadcastEvent( SystemData.Events.SEND_CHAT_TEXT )
    SocialWindowTabFriends.ResetEditBoxes()
end

---------------------------------------
-- Util Functions
---------------------------------------
function SocialWindowTabFriends.IsPlayerFriend( playerName )

    for _, friendData in ipairs( SocialWindowTabFriends.playerListData )
    do
        if( WStringsCompareIgnoreGrammer( playerName, friendData.name ) == 0 )
        then
            return true
        end
    end

    return false
end